/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.Compras;

import Controlador.Bean.Almacen.Producto;
import Controlador.Bean.Compras.CatalogoData;

import Controlador.Bean.Compras.Distrito;
import Controlador.Bean.Compras.ProductoxProveedor;
import Controlador.Bean.Compras.Proveedor;
import Controlador.Bean.Ventas.Departamento;
import Controlador.Bean.Ventas.Provincia;
import Controlador.Service.Ventas.GestionVentas;
import gui.General.Main;
import java.awt.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.swing.AbstractCellEditor;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import lib.Validaciones;
import Atxy2k.CustomTextField.RestrictedTextField;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author LiziTa
 */
public class agregarProveedor extends javax.swing.JInternalFrame {

    /**
     * Creates new form agregarProveedor
     */
       
    HashMap<String,CatalogoData> catalogo;
    
    private TableModel tb;
   public List<Distrito> distritoc=Controlador.Service.Compras.GestionCompra.seleccionarDistritos();
    ArrayList<Controlador.Bean.Ventas.Distrito> distrit=null;
    public List<ProductoxProveedor> proxprov;
    public List<Producto> productos=Controlador.Service.Almacen.GestionAlmacenes.obtenerProductos();
    
    ArrayList<Departamento> departamentos = GestionVentas.getInstance().consultarDepartamento();
    ArrayList<Provincia> provincias=null;
    ArrayList<Controlador.Bean.Ventas.Distrito> distrito=null;
    public Proveedor p;

         public agregarProveedor() {
                 initComponents();
                 initComp();
                 
//                   
//                TableRowSorter<TableModel> sorter  = new TableRowSorter<TableModel>((TableModel) tblProveedores.getModel());
//         tblProveedores.setRowSorter(sorter);
              
    }
        
        
    private static agregarProveedor myoc=null;
   
    public static agregarProveedor getInstance() {
         if(myoc == null){
                       myoc = new agregarProveedor();    
            Main.getDesktop().add(myoc); 
            myoc.setVisible(true);
               myoc.toFront();           
                    }
                    else{
                        if (myoc.isClosed()|| !myoc.isVisible()) {
                                myoc = new agregarProveedor(); 
                                Main.getDesktop().add(myoc);
                                myoc.toFront();
                                myoc.setVisible(true);
                        }
                        else
                            myoc.toFront();
                    }
        
        
        
                return myoc;
    }
         
         
 private void initComp(){
     
            tb = new TableModel();
tblProveedores.setModel(tb);
tblProveedores.setRowSelectionAllowed(true);

  
       cmbDepartamento.addItem("Seleccionar");
       for(int i=0; i<departamentos.size(); i++){
       
             cmbDepartamento.addItem(departamentos.get(i).getNombre());
        }
        cmbProvincia.setEnabled(false);
        cmbDistrito.setEnabled(false);
        
       buttonGroup1.add(rbtnCE);
       buttonGroup1.add(rbtnDNI);
       txtId.setEditable(false);
 
       tblProveedores.setDefaultRenderer(JButton.class, new MiRender());
       tblProveedores.setDefaultEditor( JButton.class, new MiEditor());
       
       //ocultar campos de la tabla =)
//       tblProveedores.getColumnModel().getColumn(0).setMaxWidth(0);
//       tblProveedores.getColumnModel().getColumn(0).setMinWidth(0);
//       tblProveedores.getColumnModel().getColumn(0).setPreferredWidth(0);
      tblProveedores.getColumnModel().getColumn(7).setMaxWidth(0);
           tblProveedores.getColumnModel().getColumn(7).setMinWidth(0);
             tblProveedores.getColumnModel().getColumn(7).setPreferredWidth(0);
            tblProveedores.getColumnModel().getColumn(8).setMaxWidth(0);
           tblProveedores.getColumnModel().getColumn(8).setMinWidth(0);
            tblProveedores.getColumnModel().getColumn(8).setPreferredWidth(0);
               tblProveedores.getColumnModel().getColumn(6).setMaxWidth(0);
           tblProveedores.getColumnModel().getColumn(6).setMinWidth(0);
            tblProveedores.getColumnModel().getColumn(6).setPreferredWidth(0);
           
            tblProveedores.getColumnModel().getColumn(10).setMaxWidth(0);
           tblProveedores.getColumnModel().getColumn(10).setMinWidth(0);
             tblProveedores.getColumnModel().getColumn(10).setPreferredWidth(0);
             tblProveedores.getColumnModel().getColumn(11).setMaxWidth(0);
           tblProveedores.getColumnModel().getColumn(11).setMinWidth(0);
             tblProveedores.getColumnModel().getColumn(11).setPreferredWidth(0);
       
             RestrictedTextField r = new RestrictedTextField(txtRuc);
             r.setLimit(11);
                RestrictedTextField r1 = new RestrictedTextField(txtTelefono);
             r1.setLimit(9);
                RestrictedTextField r2 = new RestrictedTextField(txtNumDoc);
             r2.setLimit(11);
             
             
                RestrictedTextField r3 = new RestrictedTextField(txtCorreo);
             r3.setLimit(50);
             
                RestrictedTextField r4 = new RestrictedTextField(txtNombre);
             r4.setLimit(50);
             
                RestrictedTextField r5 = new RestrictedTextField(txtApPat);
             r5.setLimit(50);
             
                RestrictedTextField r6 = new RestrictedTextField(txtApMat);
             r6.setLimit(50);
             
                RestrictedTextField r7 = new RestrictedTextField(txtDir);
                
             r7.setLimit(50);
             
             
                RestrictedTextField r8 = new RestrictedTextField(txtRazon);
                
             r8.setLimit(50);
   
    }

  
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    int clic=0;
    String selectedId;
    String id;
    String razon;
    
//     public void filtrar(String id){
//        this.id = id;
//        tb.actualizarTabla2();
//    }
      public void filtrar(String id, String razon){
        this.id = id;
        this.razon = razon;
        tb.actualizarTabla2();
    }
    
     class TableModel extends AbstractTableModel{
        
        //Two arrays used for the table data
       String[] columnNames = {"IdProveedor","Razon Social", "Direccion", "Ruc"
                        , "Contacto", "Ap.Paterno","Ap.Materno","Correo","Distrito","Telefono","tipodoc","num doc","Eliminar"};
               
        public List<Proveedor> data = Controlador.Service.Compras.GestionCompra.obtenerProveedor();
          // public List<ProductoxProveedor> data2 = Controlador.Service.Compras.GestionCompra.obtenerProdxProv();
           
         public void actualizarTabla(){
           data = Controlador.Service.Compras.GestionCompra.obtenerProveedor();
           
           fireTableDataChanged();
           
        } 
          public void actualizarTabla2(){
            data = Controlador.Service.Compras.GestionCompra.filtrarProveedor(id, razon);
                fireTableDataChanged();
                id="";
            razon="";
        }
         
        
        @Override
        public int getRowCount()
        {
         
            return data.size();
        }
        
        
        
        @Override
        public int getColumnCount()            
        {
            return columnNames.length;
        }
        
        @Override
        public Object getValueAt(int row, int column)
        {   // {"Razon Social", "Direccion", "Ruc" , "Contacto", "Apellido","Eliminar"};
            switch(column){
                case 0:return data.get(row).getIdProveedor();
                case 1: return data.get(row).getRazonSocial();
                case 2: return data.get(row).getDireccion(); 
                case 3: return data.get(row).getRuc();
                case 4: return data.get(row).getNombresContacto();
                case 5: return data.get(row).getApePaternoContacto();
                case 6: return data.get(row).getApeMaternoContacto();
                case 7: return data.get(row).getCorreo();
                case 8: return data.get(row).getIdDistrito();
                case 9: return data.get(row).getTelefono();
                              case 10:return data.get(row).getDocumentoContacto();
                    
                default: return new JButton("Eliminar");
            }
        }
        
        //Used by the JTable object to set the column names
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
        
        //Used by the JTable object to render different
        //functionality based on the data type
        @Override
        public Class getColumnClass(int c) {
            if(c!=11){
            return getValueAt(0, c).getClass();
            }else{
                return JButton.class;
            }
        }
        
        @Override
        public boolean isCellEditable(int row, int column)
        {
	        return false;
        }

       
     }
     
     
     public class MiEditor extends AbstractCellEditor implements TableCellEditor {
         private Boolean currentValue;
         @Override
         public Object getCellEditorValue()
         {
            return currentValue;
         }
         //El editor usara el propio componente. Para que funcione la celda en el modelo debe ser editable.
         @Override
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
         {
           return (JComponent) value;// la tabla solo debe tener componentes graficos
         }
     }

      public class MiRender implements TableCellRenderer {
        // Este metodo indica como debe de pintarse el elemento en la fila row, en la columna column
        // que esta en la tabla table y tiene el color dado por el objeto.
        @Override
         public Component getTableCellRendererComponent(JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) {    
            // como el boton y el calendario son componentes esto se vale.
            return (JComponent)table.getValueAt(row, column);
        }
     }
      @SuppressWarnings("unchecked")
         
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSpinner1 = new javax.swing.JSpinner();
        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        buttonGroup3 = new javax.swing.ButtonGroup();
        buttonGroup4 = new javax.swing.ButtonGroup();
        buttonGroup5 = new javax.swing.ButtonGroup();
        buttonGroup6 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtRazon = new javax.swing.JTextField();
        txtRuc = new javax.swing.JTextField();
        btnGuardar = new javax.swing.JButton();
        btnDescartar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtDir = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        txtApPat = new javax.swing.JTextField();
        cmbDistrito = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        txtTelefono = new javax.swing.JTextField();
        txtCorreo = new javax.swing.JTextField();
        txtNombre = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        txtApMat = new javax.swing.JTextField();
        lblIdProveedor = new javax.swing.JLabel();
        txtId = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        cmbDepartamento = new javax.swing.JComboBox();
        cmbProvincia = new javax.swing.JComboBox();
        rbtnDNI = new javax.swing.JRadioButton();
        rbtnCE = new javax.swing.JRadioButton();
        jLabel8 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        txtNumDoc = new javax.swing.JTextField();
        jLabel14 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblProveedores = new javax.swing.JTable();

        setClosable(true);
        setIconifiable(true);
        setTitle("Agregar Proveedor");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Detalles de proveedor"));

        jLabel1.setText("Razon Social");

        txtRazon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtRazonActionPerformed(evt);
            }
        });

        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnDescartar.setText("Descartar");
        btnDescartar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDescartarActionPerformed(evt);
            }
        });

        jLabel3.setText("RUC");

        jLabel5.setText("Direccion");

        jLabel6.setText("Distrito");

        jLabel7.setText("Nombre contacto");

        cmbDistrito.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbDistritoActionPerformed(evt);
            }
        });

        jLabel9.setText("Celular");

        jLabel10.setText("Correo");

        jLabel11.setText("Apellido Paterno");

        jLabel12.setText("Apellido Materno");

        lblIdProveedor.setText("IdProveedor");

        jButton1.setText("Buscar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("Provincia");

        jLabel4.setText("Departamento");

        cmbDepartamento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbDepartamentoActionPerformed(evt);
            }
        });

        cmbProvincia.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbProvinciaActionPerformed(evt);
            }
        });

        rbtnDNI.setText("DNI");

        rbtnCE.setText("C.EXTRANJERIA");

        jLabel8.setText("Tipo Doc.");

        jLabel13.setText("Num.Doc.");

        jLabel14.setText("(11 dígitos)");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6)
                            .addComponent(jLabel2))
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGap(9, 9, 9)
                                .addComponent(txtRuc, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(cmbDistrito, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtDir, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(cmbProvincia, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel14))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblIdProveedor)
                            .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtRazon, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cmbDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel11, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel12)
                        .addComponent(jLabel13, javax.swing.GroupLayout.Alignment.TRAILING))
                    .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtApPat)
                    .addComponent(txtNombre)
                    .addComponent(txtApMat)
                    .addComponent(txtCorreo)
                    .addComponent(txtTelefono)
                    .addComponent(txtNumDoc)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(rbtnDNI)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rbtnCE)))
                .addGap(28, 28, 28))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(18, 18, 18)
                .addComponent(btnGuardar)
                .addGap(18, 18, 18)
                .addComponent(btnDescartar)
                .addGap(240, 240, 240))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtId)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblIdProveedor)
                        .addComponent(jLabel9)
                        .addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtRazon)
                    .addComponent(jLabel10)
                    .addComponent(txtCorreo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(txtRuc)
                    .addComponent(jLabel3)
                    .addComponent(jLabel14))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtApPat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11)
                    .addComponent(txtDir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(txtApMat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(cmbDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(rbtnCE)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(rbtnDNI)
                                .addComponent(jLabel8)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtNumDoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel13)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(cmbProvincia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(cmbDistrito, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(btnGuardar)
                    .addComponent(btnDescartar))
                .addGap(35, 35, 35))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        tblProveedores.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        tblProveedores.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblProveedores.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblProveedoresMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblProveedores);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 665, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(35, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

       public boolean valido(){
           boolean correo = Validaciones.validarEmail(txtCorreo.getText());
        boolean telefono = Validaciones.validarEntero(txtTelefono.getText());
        boolean ruc = Validaciones.validarEntero(txtRuc.getText());
        boolean nombre = Validaciones.validarNombre(txtNombre.getText());
        boolean apm=Validaciones.validarNombre(txtApMat.getText());
        boolean app=Validaciones.validarNombre(txtApPat.getText());
        
        boolean b = true;
        String n1 = "";
        String n2="";
        String n3 = "";
        String n4="";
        String n5 = "";
        String n6="";
        String n7 = "";
        String n8="";
        String n9 = "";
        String n10="";
      
       String n12="";
        //campos vacios
        
        if(txtRazon.getText().isEmpty() || txtCorreo.getText().isEmpty()|| 
                txtTelefono.getText().isEmpty()||txtNombre.getText().isEmpty() ||txtApMat.getText().isEmpty()||
                txtRuc.getText().isEmpty() ||txtApPat.getText().isEmpty() || txtRazon.getText().isEmpty()
                || txtNumDoc.getText().isEmpty() || (!rbtnCE.isSelected() && !rbtnDNI.isSelected()))
            {
            b = false;
             n12 ="Los campos no deben estar vacios";
        }
                
        if(rbtnCE.isSelected() && txtNumDoc.getText().isEmpty()){
            b = false;
            n1 = "Ingresar numero de C.Extranjeria";
        }
        if(rbtnDNI.isSelected() && txtNumDoc.getText().isEmpty()){
            b = false;
             n2 = "Ingresar numero de DNI";
        }
          if(rbtnDNI.isSelected() && txtNumDoc.getText().length()!=8 && !txtNumDoc.getText().isEmpty()){
            b = false;
           n3 = "DNI debe tener 8 digitos";
        }
            if(rbtnCE.isSelected() && txtNumDoc.getText().length()!=11 && !txtNumDoc.getText().isEmpty() ){
            b = false;
          n4 =  "C.E debe tener 11 digitos";
        }
        
                         
        if(cmbDepartamento.getSelectedIndex()<1){
            b = false;
            n5 = "Seleccionar Departamento";
        }
        if(cmbProvincia.getSelectedIndex()<1){
            b = false;
           n6 =  "Seleccionar Provincia";
        }
        if(cmbDistrito.getSelectedIndex()<1){
            b = false;
           n7 = "Seleccionar Distrito";
        }
       
        if( !ruc|| txtRuc.getText().length()!=11 && !txtRuc.getText().isEmpty() ){
            b = false;
           n8 ="RUC solo permite numeros y 11 dígitos" ;
        }
               
        
        if(  !correo){
            b = false;
           n9 = "Error en formato de correo";
        }
         if( !telefono || txtTelefono.getText().length()!=9 &&  !txtTelefono.getText().isEmpty()){

            b = false;
            n10 ="Celular solo permite numeros y 9 digitos";
        }
        
         String rpta="";
         if (n12!="") rpta = rpta+ n12 + "\n";
         if (n1!="") rpta = rpta+ n1 + "\n";
         if (n2!="") rpta = rpta+ n2 + "\n";
         if (n3!="") rpta = rpta+ n3 + "\n";
         if (n4!="") rpta = rpta+ n4 + "\n";
         if (n5!="") rpta = rpta+ n5 + "\n";
         if (n6!="") rpta = rpta+ n6 + "\n";
         if (n7!="") rpta = rpta+ n7 + "\n";
         if (n8!="") rpta = rpta+ n8 + "\n";
         if (n9!="") rpta = rpta+ n9 + "\n";
         if (n10!="") rpta = rpta+ n10 + "\n";
         
                
         if (rpta!="")
         JOptionPane.showMessageDialog(null, "Errores: \n" + rpta );
            
        return b;
    }
      
      
    private void cmbDistritoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbDistritoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbDistritoActionPerformed

    private void btnDescartarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDescartarActionPerformed
        // TODO add your handling code here:
        txtId.setText("");
        txtRazon.setText("");
        txtRuc.setText("");
        txtDir.setText("");
        txtNumDoc.setText("");
        txtTelefono.setText("");
        txtCorreo.setText("");
        txtNombre.setText("");
        txtApPat.setText("");
        txtApMat.setText("");
        cmbDepartamento.setSelectedIndex(0);
        cmbProvincia.setEditable(false);
        cmbDistrito.setEditable(false);
        rbtnDNI.setSelected(false);
        rbtnCE.setSelected(false);
        
    }//GEN-LAST:event_btnDescartarActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // TODO add your handling code here:
        
              
            if (valido()){
       
               
           if (rbtnDNI.isSelected()){  
              p= new Proveedor( txtId.getText(),txtRazon.getText(),txtRuc.getText(),txtDir.getText(),distrito.get(cmbDistrito.getSelectedIndex()-1).getIdDistrito(),
                Integer.parseInt(txtTelefono.getText()),txtCorreo.getText(),
                txtNombre.getText(),txtApPat.getText(),txtApMat.getText(),"DNI",txtNumDoc.getText(),"1");
            }else if (rbtnCE.isSelected()) {
             p= new Proveedor( txtId.getText(),txtRazon.getText(),txtRuc.getText(),txtDir.getText(),distrito.get(cmbDistrito.getSelectedIndex()-1).getIdDistrito(),
                Integer.parseInt(txtTelefono.getText()),txtCorreo.getText(),
                txtNombre.getText(),txtApPat.getText(),txtApMat.getText(),"PASAPORTE",txtNumDoc.getText(),"1");
             }
            
                     
            if(txtId.getText().isEmpty()){
                Controlador.Service.Compras.GestionCompra.agregarProveedor(p);
            }else{
                Controlador.Service.Compras.GestionCompra.actualizarProveedor(p);
            }
            
             txtId.setText("");
        txtRazon.setText("");
        txtRuc.setText("");
        txtDir.setText("");
        cmbDepartamento.setSelectedIndex(0);
        cmbProvincia.setEditable(false);
        cmbDistrito.setEditable(false);
        rbtnDNI.setSelected(false);
        rbtnCE.setSelected(false);
        txtNumDoc.setText("");
        txtTelefono.setText("");
        txtCorreo.setText("");
        txtNombre.setText("");
        txtApPat.setText("");
        txtApMat.setText("");
            
            tb.actualizarTabla();
            JOptionPane.showMessageDialog(null,"Datos agregados");
            
            }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void txtRazonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtRazonActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtRazonActionPerformed

    private void tblProveedoresMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblProveedoresMouseClicked

        String departamento;
    String provincia;
        ArrayList<String> prov;
        int selectedRowIndex = tblProveedores.getSelectedRow();
        int selectedColumnIndex = tblProveedores.getSelectedColumn();
        if(selectedColumnIndex!=11){
            String selectId = (String) tblProveedores.getValueAt(selectedRowIndex, 0);

            if(clic == 1 && selectedId.compareTo(selectId)==0){
               txtId.setText((String)tblProveedores.getValueAt(selectedRowIndex, 0));
                txtRazon.setText((String)tblProveedores.getValueAt(selectedRowIndex, 1));
                txtDir.setText((String)tblProveedores.getValueAt(selectedRowIndex, 2));
                txtRuc.setText((String)tblProveedores.getValueAt(selectedRowIndex, 3));
                txtNombre.setText((String)tblProveedores.getValueAt(selectedRowIndex, 4));
                txtApPat.setText((String)tblProveedores.getValueAt(selectedRowIndex, 5));
                txtApMat.setText((String)tblProveedores.getValueAt(selectedRowIndex, 6));
                txtCorreo.setText((String)tblProveedores.getValueAt(selectedRowIndex, 7));
//txtTipoDocumento.setText((String)tblProveedores.getValueAt(selectedRowIndex, 10));
                txtNumDoc.setText((String)tblProveedores.getValueAt(selectedRowIndex, 10));
                String NumDoc=(String)tblProveedores.getValueAt(selectedRowIndex, 10);
                if (NumDoc.length()==8)  rbtnDNI.setSelected(true);
                else
                    rbtnCE.setSelected(true);
                    
                    
                String distr=(String)tblProveedores.getValueAt(selectedRowIndex, 8);
                
                provincia = Controlador.Service.Ventas.GestionVentas.getInstance().obtenerProvincia(distr);
        departamento = Controlador.Service.Ventas.GestionVentas.getInstance().obtenerDepartamento(provincia);
                
        //CMB DEPARTAMENTO
        cmbDepartamento.addItem("Seleccionar");      
        for(int i=0; i<departamentos.size(); i++){
             cmbDepartamento.addItem(departamentos.get(i).getNombre());
             if(departamento.equals(departamentos.get(i).getIdDepartamento()))
                 cmbDepartamento.setSelectedIndex(i+1);
        }
        //CMB PROVINCIA
        cmbProvincia.addItem("Seleccionar");
        provincias=GestionVentas.getInstance().consultarProvincia(departamentos.get(cmbDepartamento.getSelectedIndex()-1).getIdDepartamento());
        for(int i=0; i<provincias.size(); i++){
            cmbProvincia.addItem(provincias.get(i).getNombre());
            if(provincia.equals(provincias.get(i).getIdProvincia()))
                 cmbProvincia.setSelectedIndex(i+1);
        }
        //CMB DISTRITO
        cmbDistrito.addItem("Seleccionar");
        distrit=GestionVentas.getInstance().consultarDistrito(provincias.get(cmbProvincia.getSelectedIndex()-1).getIdProvincia());
        for(int i=0; i<distrit.size(); i++){
            cmbDistrito.addItem(distrit.get(i).getNombre());
            if(distr.equals(distrit.get(i).getIdDistrito()))
                 cmbDistrito.setSelectedIndex(i+1);
        }
                
                 // cmbDistrito.setSelectedIndex(Integer.parseInt((String)tblProveedores.getValueAt(selectedRowIndex, 8)));
                     txtTelefono.setText(((Integer)tblProveedores.getValueAt(selectedRowIndex, 9)).toString());
                clic = 0;
                //cmbDistrito.setEnabled(true);
            }else if(clic == 0){
                selectedId = selectId;
                clic++;
            }else{
                clic = 0;
            }
        }
        
        if (selectedColumnIndex==12){
            int confirmado = JOptionPane.showConfirmDialog(this,"¿Desea eliminar el proveedor?");
            if (confirmado == JOptionPane.OK_OPTION){
                //VALIDA PROVEEDOR UNIDO A OC o CATALOGO
       //         int cond = Controlador.Service.Compras.GestionCompra.eliminarProveedores((String)tblProveedores.getValueAt(selectedRowIndex, 0));
         //      if(cond == 1){
           //         JOptionPane.showMessageDialog(this, "El proveedor que desea eliminar está siendo utilizado");
            //    } tb.actualizarTabla();
            }
        }

        // TODO add your handling code here:
    }//GEN-LAST:event_tblProveedoresMouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

         BuscarProv bP = new BuscarProv(this);
        Main.getDesktop().add(bP);
        bP.setVisible(true);
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void cmbDepartamentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbDepartamentoActionPerformed
       
        // TODO add your handling code here:
       
         if(cmbDepartamento.getSelectedIndex()>0){
            cmbProvincia.removeAllItems();
            cmbDistrito.removeAllItems();
            cmbProvincia.setEnabled(true);
            cmbDistrito.setEnabled(false);
            cmbProvincia.addItem("Seleccionar");
            
            provincias=GestionVentas.getInstance().consultarProvincia(departamentos.get(cmbDepartamento.getSelectedIndex()-1).getIdDepartamento());
            for(int i=0; i<provincias.size(); i++){
                cmbProvincia.addItem(provincias.get(i).getNombre());
            }
        }
        else{
            cmbProvincia.setEnabled(false);
            cmbDistrito.setEnabled(false);
            cmbProvincia.removeAllItems();
            cmbDistrito.removeAllItems();    
        }
    }//GEN-LAST:event_cmbDepartamentoActionPerformed

    private void cmbProvinciaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbProvinciaActionPerformed
        // TODO add your handling code here:
         if(cmbProvincia.getSelectedIndex()>0){
            cmbDistrito.removeAllItems();
            cmbDistrito.setEnabled(true);
            cmbDistrito.addItem("Seleccionar");
            distrito=GestionVentas.getInstance().consultarDistrito(provincias.get(cmbProvincia.getSelectedIndex()-1).getIdProvincia());
            for(int i=0; i<distrito.size(); i++){
             cmbDistrito.addItem(distrito.get(i).getNombre());
            }
        }
        else{
            cmbDistrito.setEnabled(false);
            cmbDistrito.removeAllItems(); 
        }
        
    }//GEN-LAST:event_cmbProvinciaActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDescartar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.ButtonGroup buttonGroup3;
    private javax.swing.ButtonGroup buttonGroup4;
    private javax.swing.ButtonGroup buttonGroup5;
    private javax.swing.ButtonGroup buttonGroup6;
    private javax.swing.JComboBox cmbDepartamento;
    private javax.swing.JComboBox cmbDistrito;
    private javax.swing.JComboBox cmbProvincia;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSpinner jSpinner1;
    private javax.swing.JLabel lblIdProveedor;
    private javax.swing.JRadioButton rbtnCE;
    private javax.swing.JRadioButton rbtnDNI;
    private javax.swing.JTable tblProveedores;
    private javax.swing.JTextField txtApMat;
    private javax.swing.JTextField txtApPat;
    private javax.swing.JTextField txtCorreo;
    private javax.swing.JTextField txtDir;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtNumDoc;
    private javax.swing.JTextField txtRazon;
    private javax.swing.JTextField txtRuc;
    private javax.swing.JTextField txtTelefono;
    // End of variables declaration//GEN-END:variables
 }
